package com.xhxi.photobooker.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xhxi.photobooker.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AiChatService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String REDIS_KEY_PREFIX = "ai:chat:history:";
    // Ollama API地址和模型名
    private static final String OLLAMA_API_URL = "http://localhost:11434/api/chat";
    private static final String MODEL = "qwen2:1.5b";

    public String chat(String sessionId, String userMessage) {
        String systemPrompt = "你是智能ai，你的名字叫‘小影’。无论用户问什么，你都要以‘小影’自称.如果你不知道答案，请礼貌地说你不确定，但会帮用户记录反馈。请记住，每次回复都要以‘小影’自称。";
        String redisKey = REDIS_KEY_PREFIX + sessionId;
        String historyJson = (String) redisTemplate.opsForValue().get(redisKey);
        List<Map<String, String>> history = null;
        if (historyJson != null) {
            history = JSON.parseObject(historyJson, new TypeReference<List<Map<String, String>>>(){});
        } else {
            history = new ArrayList<>();
            Map<String, String> sysMsg = new HashMap<>();
            sysMsg.put("role", "system");
            sysMsg.put("content", systemPrompt);
            history.add(sysMsg);
        }
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", userMessage);
        history.add(userMsg);

        // 构造Ollama请求体
        Map<String, Object> req = new HashMap<>();
        req.put("model", MODEL);
        List<Map<String, String>> messages = new ArrayList<>();
        for (Map<String, String> msg : history) {
            Map<String, String> m = new HashMap<>();
            m.put("role", msg.get("role"));
            m.put("content", msg.get("content"));
            messages.add(m);
        }
        req.put("messages", messages);
        req.put("temperature", 0.7);
        req.put("max_tokens", 512);
        req.put("stream", false);

        String reply = "";
        try {
            String resp = HttpClientUtil.doPost4Json(OLLAMA_API_URL, req);
            JSONObject respObj = JSONObject.parseObject(resp);
            JSONObject messageObj = respObj.getJSONObject("message");
            reply = messageObj.getString("content");
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细异常
            reply = "AI服务暂时不可用，请稍后再试。";
        }
        Map<String, String> aiMsg = new HashMap<>();
        aiMsg.put("role", "assistant");
        aiMsg.put("content", reply);
        history.add(aiMsg);
        if (history.size() > 20) {
            history.subList(1, history.size() - 18).clear();
        }
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(history), 1, TimeUnit.HOURS);
        return reply;
    }
} 